const { getOrders, getOrderDetail, insertOrder, updateOrder } = require('../models/Order');
const pool = require('../config/db');

const getUserOrders = async (req, res) => {
    try {
        const userId = req.user.userId;
        const orders = await getOrders(userId);
        res.json({
            success: true,
            code: 200,
            data: orders,
            message: '获取订单列表成功'
        });
    } catch (error) {
        console.error('[ORDER] 获取订单列表失败:', error);
        res.status(500).json({ 
            success: false,
            code: 500,
            message: '服务器内部错误' 
        });
    }
};

const getOrderById = async (req, res) => {
    try {
        const orderId = req.params.id;
        const userId = req.user.userId;
        
        const order = await getOrderDetail(orderId, userId);
        
        if (!order) {
            return res.status(404).json({
                success: false,
                code: 404,
                message: '订单不存在'
            });
        }
        
        res.json({
            success: true,
            code: 200,
            data: order,
            message: '获取订单详情成功'
        });
    } catch (error) {
        console.error('[ORDER] 获取订单详情失败:', error);
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

const createOrder = async (req, res) => {
    try {
        const userId = req.user.userId;
        const orderData = {
            ...req.body,
            user_id: userId,
            status: 'pending',
            create_time: new Date()
        };
        
        const orderId = await insertOrder(orderData);
        
        res.status(201).json({
            success: true,
            code: 200,
            data: { id: orderId },
            message: '创建订单成功'
        });
    } catch (error) {
        console.error('[ORDER] 创建订单失败:', error);
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

const updateOrderStatus = async (req, res) => {
    try {
        const orderId = req.params.id;
        const userId = req.user.userId;
        const { status } = req.body;
        
        if (!status) {
            return res.status(400).json({
                success: false,
                code: 400,
                message: '缺少状态参数'
            });
        }
        
        // 验证状态值是否合法
        const validStatuses = ['pending', 'paid', 'shipping', 'completed', 'cancelled'];
        if (!validStatuses.includes(status)) {
            return res.status(400).json({
                success: false,
                code: 400,
                message: '无效的状态值'
            });
        }
        
        const result = await updateOrder(orderId, userId, { status });
        
        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                code: 404,
                message: '订单不存在或无权限更新'
            });
        }
        
        res.json({
            success: true,
            code: 200,
            message: '更新订单状态成功'
        });
    } catch (error) {
        console.error('[ORDER] 更新订单状态失败:', error);
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

const getOrderStats = async (req, res) => {
    try {
        const userId = req.user.userId;
        
        // 使用原生SQL查询获取各状态订单数量
        const [rows] = await pool.execute(
            `SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid,
                SUM(CASE WHEN status = 'shipping' THEN 1 ELSE 0 END) as shipping,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled
            FROM orders 
            WHERE user_id = ?`,
            [userId]
        );
        
        res.json({
            success: true,
            code: 200,
            ...rows[0],
            message: '获取订单统计成功'
        });
    } catch (error) {
        console.error('[ORDER] 获取订单统计失败:', error);
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

module.exports = { getUserOrders, getOrderById, getOrderStats, createOrder, updateOrderStatus };